<template>
  <el-dialog
          :model-value="relGoodsVisible"
          title="媒资关联商品"
          :before-close="cancelRelGoodsDialog"
          width="70%"
  >
    <table-header
            :queryList="queryList"
            :rightColSpan="4"
            :leftColSpan="20"
            placeholder="请输入商品名称"
            @pagination="getGoodsDataList"
            label="keywords"
    >
      <template #operation>
        <span></span>
      </template>
    </table-header>
    <el-row class="mt10 mb10">
      <el-col :span="24">
        <el-table
                ref="dialogRelGoodsRef"
                v-loading="isloading"
                style="width: 100%"
                border
                :data="tableData.listData"
                @row-click="handleRowClick"
                @select="handleSelect"
                @select-all="handleSelectAll"
        >
          <el-table-column type="selection" align="center" width="55" :selectable="handleSelectAble"/>
          <el-table-column label="海报预览" align="center">
            <template #default="{row}">
              <span @click.stop>
                <el-image
                        :src="row.imgurl_150"
                        :preview-src-list="imgSrcList"
                        :initial-index="initialIndex(row.imgurl_720)"
                />
              </span>
            </template>
          </el-table-column>
          <el-table-column label="商品ID" width="80" prop="goods_id" />
          <el-table-column label="商品名称" prop="goods_name" show-overflow-tooltip />
          <el-table-column label="商品货号" prop="goods_sn" />
          <el-table-column label="市场价" width="100">
            <template #default="{row}">
              {{row.market_price}} ￥
            </template>
          </el-table-column>
          <el-table-column label="实际售价" width="100">
            <template #default="{row}">
              {{row.goods_price}} ￥
            </template>
          </el-table-column>
          <el-table-column label="供应商" prop="supplier" width="100"/>
           <el-table-column label="商品状态" width="100">
             <template #default="{row}">
               <el-tag type="success" size="mini" v-if="row.state == 1">上架</el-tag>
               <el-tag type="danger" size="mini" v-else>下架</el-tag>
             </template>
           </el-table-column>
          <el-table-column label="创建时间" width="150">
            <template #default="{row}">
              {{row.ctime ? row.ctime.replace('T', ' ') : '--'}}
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="24">
        <table-pagination
                :queryList="queryList"
                :total="tableData.total"
                @pagination="getGoodsDataList"
        />
      </el-col>
    </el-row>
    <template #footer>
      <div align="center">
        <el-button size="mini" type="default" @click="cancelRelGoodsDialog">取消</el-button>
        <el-button size="mini" type="primary" @click="confirmRelGoods">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
  import {ref, reactive, toRef, computed, nextTick} from 'vue'
  import {useStore} from 'vuex'
  import TableHeader from "@/views/public/TableHeader";
  import TablePagination from "@/views/public/TablePagination";
  import {getGoodsList} from "@/api/media/goods";
  import {ElMessage} from 'element-plus'
  import {createMediaRelGoods, createSeriesRelGoods} from "@/api/goods/relgoods";

  export default {
    name: "MediaRelGoods",
    components: {TableHeader, TablePagination},
    props: {
      relGoodsFormData: {
        type: Object,
        default() {
          return {
            mediaid: undefined,
            seriesid: undefined,
            datas: []
          }
        }
      },
      relGoodsVisible: {
        type: Boolean,
        default: false
      },
      relGoodsOperationType: {
        type: String,
        default: 'refgoods'
      },
      goodsIds: {
        type: Array,
        default() {
          return []
        }
      }
    },
    emits: ['cancelRelGoodsDialog', 'handleConfirmSelectedGoods'],
    setup(props, context) {
      const store = useStore()
      const corpid = store.getters.corpinfo.corpid
      const goodsFormData = toRef(props, 'relGoodsFormData')
      const queryList = reactive({
        corpid: corpid,
        page: 1,
        pagesize: 25,
        keywords: undefined,
        sort: 'mts',
        sorttype: 'desc'
      })
      const tableData = reactive({
        total: 0,
        listData: []
      })
      const isloading = ref(false)
      const dialogRelGoodsRef = ref(null)
      const goodsDataList = ref([])
      const imgSrcList = ref([])

      const initialIndex = computed(() => {
        return (src) => {
          return imgSrcList.value.findIndex(d => d === src)
        }
      })

      /** 获取商品列表 **/
      const getGoodsDataList = () => {
        isloading.value = true
        getGoodsList(queryList).then(response => {
          isloading.value = false
          const {total, list} = response.data
          tableData.total = total
          tableData.listData = list
          imgSrcList.value = []
          nextTick(() => {
            tableData.listData.forEach(row => {
              if (props.goodsIds.includes(row.goods_id)) {
                dialogRelGoodsRef.value.toggleRowSelection(row, true)
              }
              if (row.imgurl_720) {
                imgSrcList.value.push(row.imgurl_720)
              }
            })
          })
        })
      }
      /** 关闭弹框 **/
      const cancelRelGoodsDialog = () => {
        context.emit('cancelRelGoodsDialog')
      }
      /** 过滤数据 **/
      const handleFilterGoods = () => {
        queryList.page = 1
        getGoodsDataList()
      }
      /** 点击单行 **/
      const handleRowClick = (row) => {
        if (!props.goodsIds.includes(row.goods_id)) {
          handleGetSelectedGoodsId(row)
          if (goodsFormData.value.datas.includes(row.goods_id)) {
            dialogRelGoodsRef.value.toggleRowSelection(row, true)
          } else {
            dialogRelGoodsRef.value.toggleRowSelection(row, false)
          }
        }
      }
      /** 选择数据行 **/
      const handleSelect = (selection, row) => {
        handleGetSelectedGoodsId(row)
      }
      /** 全选 **/
      const handleSelectAll = (selection) => {
        if (selection.length > 0) {
          selection.forEach(row => {
            if (!goodsFormData.value.datas.includes(row.goods_id)) {
              goodsFormData.value.datas.push(row.goods_id)
            }
          })
        } else {
          goodsFormData.value.datas = []
        }
      }
      /** 获取选择的商品ID **/
      const handleGetSelectedGoodsId = (row) => {
        if (goodsFormData.value.datas.includes(row.goods_id)) {
          const index = goodsFormData.value.datas.findIndex(d => d == row.goods_id)
          goodsFormData.value.datas.splice(index, 1)
        } else {
          goodsFormData.value.datas.push(row.goods_id)
        }
      }
      /** 获取商品详细信息 **/
      const handleGetGoodsDetail = () => {
        goodsDataList.value = []
        tableData.listData.forEach(row => {
          if (goodsFormData.value.datas.includes(row.goods_id)) {
            goodsDataList.value.push(row)
          }
        })
      }
      /** 是否可选 **/
      const handleSelectAble = (row) => {
        return !props.goodsIds.includes(row.goods_id)
      }
      /** 确定关联商品 **/
      const confirmRelGoods = () => {
        if (goodsFormData.value.datas.length <= 0) {
          ElMessage({type: 'warning', message: '请选择商品', duration: 2000})
        } else {
          if (props.relGoodsOperationType == 'refgoods') {
            if (goodsFormData.value.mediaid !== undefined) {
              createMediaRelGoods(goodsFormData.value).then(response => {
                if (response.errcode == 0) {
                  ElMessage({type: 'success', message: response.msg, duration: 2000})
                  context.emit('handleConfirmSelectedGoods')
                  cancelRelGoodsDialog()
                }
              })
            } else if (goodsFormData.value.seriesid !== undefined) {
              createSeriesRelGoods(goodsFormData.value).then(response => {
                if (response.errcode == 0) {
                  ElMessage({type: 'success', message: response.msg, duration: 2000})
                  context.emit('handleConfirmSelectedGoods')
                  cancelRelGoodsDialog()
                }
              })
            }
          } else {
            handleGetGoodsDetail()
            context.emit('handleConfirmSelectedGoods', goodsDataList.value)
            cancelRelGoodsDialog()
          }
        }
      }
      return {
        queryList,
        tableData,
        isloading,
        cancelRelGoodsDialog,
        handleFilterGoods,
        getGoodsDataList,
        handleRowClick,
        handleSelectAll,
        handleSelect,
        dialogRelGoodsRef,
        confirmRelGoods,
        imgSrcList,
        initialIndex,
        handleSelectAble
      }
    }
  }
</script>

<style scoped>

</style>
